package com.jman.register.controller.checkCode;


import com.jman.register.util.CheckCodeUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 撰写请求服务器端生成验证码的资源
 * 验证码为图片形式
 */

@CrossOrigin
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成验证码，并存入redis当中
        String verifyCode = CheckCodeUtil.generateVerifyCode(4);
        stringRedisTemplate.opsForValue().set("register:code", verifyCode, 2, TimeUnit.MINUTES);

        //response输出验证码数据
        ServletOutputStream os = response.getOutputStream();
        CheckCodeUtil.outputImage(80, 40, os, verifyCode);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}